package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParser;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.CustomExcetionCast;
import com.xuecheng.framework.model.response.CommonCode;
import jdk.nashorn.internal.parser.JSONParser;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.rmi.MarshalledObject;
import java.util.Map;

@Service
public class FileUploadService {
    @Autowired
    FileSystemRepository fileSystemRepository;

    //    注入初始化参数
    @Value("${xuecheng.fastdfs.tracker_servers}")
    String tracker_servers;
    @Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    @Value("${xuecheng.fastdfs.charset}")
    String charset;


    /**
     * @Description: 单文件上传
     * @Param: multipart
     * @return: UploadFileResult
     * @Author: Mr.Yuan
     * @Date:
     */
    public UploadFileResult fileUpload(MultipartFile file, String userId, String businesskey, String filetag, String metadata) {
        if (file == null) {
            throw CustomExcetionCast.getCusException(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }

        //       初始化fastdfs
        this.initFastDfs();
        String originalFilename = file.getOriginalFilename();
        String extname = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String uploadFile1;
        try {
            //        创建tracker客户端
            TrackerClient trackerClient = new TrackerClient();
//        获取tracke服务器连接
            TrackerServer trackerClientConnection = trackerClient.getConnection();
//            获取storge服务器
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerClientConnection);
//            创建storge客户端
            StorageClient1 storageClient1 = new StorageClient1(trackerClientConnection, storeStorage);

            //            进行上传准备工作
            byte[] bytes = file.getBytes();

            uploadFile1 = storageClient1.upload_file1(bytes, extname, null);


        } catch (Exception e) {
            e.printStackTrace();
            return new UploadFileResult(FileSystemCode.FS_UPLOADFILE_SERVERFAIL,null);
        }
//        将上传的文件保存到数据库中
        long fileSize = file.getSize();
        Map parse = (Map) JSON.parse(metadata);
        FileSystem fileSystem=new FileSystem();
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFileId(uploadFile1);
        fileSystem.setFilePath(uploadFile1);
        fileSystem.setUserId(userId);
        fileSystem.setMetadata(parse);
        fileSystem.setFiletag(filetag);
        fileSystem.setFileName(originalFilename);
        fileSystem.setFileSize(fileSize);

        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }

    /**
     * @Description: 初始化fastdfs
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private void initFastDfs() {
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
        } catch (Exception e) {
            e.printStackTrace();
            throw CustomExcetionCast.getCusException(FileSystemCode.FS_UPLOADFILE_INITERROR);
        }

    }
}